use anyhow::Result;
use colored::*;
use serde_json::Value;
use std::fs;

pub async fn run(package_path: String) -> Result<()> {
    println!("{} {}", "📦 Analyzing".cyan(), package_path);

    let content = fs::read_to_string(&package_path)?;
    let package: Value = serde_json::from_str(&content)?;

    if let Some(deps) = package.get("dependencies").and_then(|d| d.as_object()) {
        println!("\n{}", "📋 Dependencies:".blue().bold());
        for (name, version) in deps {
            println!(
                "  {} {}",
                name.green(),
                version.as_str().unwrap_or("unknown")
            );
        }
        println!("  {} Total: {}", "📊".blue(), deps.len());
    }

    if let Some(dev_deps) = package.get("devDependencies").and_then(|d| d.as_object()) {
        println!("\n{}", "🛠️  Dev Dependencies:".yellow().bold());
        for (name, version) in dev_deps {
            println!(
                "  {} {}",
                name.yellow(),
                version.as_str().unwrap_or("unknown")
            );
        }
        println!("  {} Total: {}", "📊".yellow(), dev_deps.len());
    }

    // 检查常见问题
    check_common_issues(&package)?;

    Ok(())
}

fn check_common_issues(package: &Value) -> Result<()> {
    println!("\n{}", "🔍 Health Check:".magenta().bold());

    // 检查是否有 package-lock.json 的提醒
    if !std::path::Path::new("package-lock.json").exists()
        && !std::path::Path::new("yarn.lock").exists()
    {
        println!(
            "  {} No lock file found (package-lock.json or yarn.lock)",
            "⚠️".yellow()
        );
    } else {
        println!("  {} Lock file found", "✅".green());
    }

    // 检查 scripts
    if let Some(scripts) = package.get("scripts").and_then(|s| s.as_object()) {
        if scripts.contains_key("test") {
            println!("  {} Test script configured", "✅".green());
        } else {
            println!("  {} No test script found", "⚠️".yellow());
        }

        if scripts.contains_key("build") {
            println!("  {} Build script configured", "✅".green());
        } else {
            println!("  {} No build script found", "⚠️".yellow());
        }
    }

    Ok(())
}
